<?php

namespace App\Models\Common\Channel\Repositories;

use App\Models\Common\Channel\Channel;
use App\Models\Common\Channel\Repositories\Interfaces\ChannelRepositoryInterface;
use App\Trip\Repository\BaseRepository;
use Illuminate\Support\Facades\Cache;

class ChannelRepository extends BaseRepository implements ChannelRepositoryInterface
{

    public function __construct(Channel $channel)
    {
        parent::__construct($channel);
    }

    public function addChannel(array $data): Channel
    {
        if ($channel = $this->findChannelByAppId($data['appid'])) {
            $this->update($data, $channel);
            $channel->refresh();
            return $channel;
        }
        return $this->create($data);
    }

    public function findChannelByAppId(string $appid): ?Channel
    {
        $cache_key = "Channel:appid:{$appid}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $channel = $this->findOneBy([
            'appid' => $appid,
        ]);
        $channel && Cache::forever($cache_key, $channel);
        return $channel;
    }

    public function findChannel(int $channelId): Channel
    {
        $cache_key = "Channel:id:{$channelId}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $channel = $this->findOneOrFail($channelId);
        Cache::forever($cache_key, $channel);
        return $channel;
    }

    public function deleteChannel(Channel $channel): bool
    {
        return $channel->delete();
    }
}